package com.sdcqjy.mylibrary.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RadioButton;

import com.sdcqjy.mylibrary.R;

public class TabRadioButton extends RadioButton {
    public TabRadioButton(Context context) {
        super(context);
        init(context);
    }

    public TabRadioButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.attrs = attrs;
        init(context);
    }

    public TabRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.attrs = attrs;
        init(context);
    }

    private AttributeSet attrs;
    private int fillColor;
    private float fillWidth;
    private float fillHeight;
    private Paint paint;
    private Drawable drawable;

    public void setFillColor(int fillColor) {
        this.fillColor = fillColor;
        invalidate();
    }

    private void init(Context context) {
        if (attrs != null) {
            TypedArray a = context.obtainStyledAttributes(attrs,
                    R.styleable.TabRadioButton);
            fillHeight = a.getDimension(R.styleable.TabRadioButton_fillHeight, 0);
            fillWidth = a.getDimension(R.styleable.TabRadioButton_fillWidth, 0);
            fillColor = a.getColor(R.styleable.TabRadioButton_fillColor, 0);
            drawable = a.getDrawable(R.styleable.TabRadioButton_fillBitmap);
            attrs = null;
        }
        paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(fillColor);
//        paint.setColor(0xFF379BF0);
    }

    public void setChecked(boolean checked) {
        super.setChecked(checked);
        invalidate();
    }

    protected void onDraw(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();
        if (width <= 0 || height <= 0) return;
        //paint.setColor(getCurrentTextColor());
        // float hTmp=isChecked()?fillHeight:1;
        super.onDraw(canvas);
        if (isChecked()) {
            if (fillHeight > 0) {
                if (fillWidth > 0) {
                    float v = (width - fillWidth) / 2.0f;
                    canvas.drawRect(v, height - fillHeight, width - v, height, paint);
                } else canvas.drawRect(0, height - fillHeight, width, height, paint);
            }
            if (drawable != null) {
                int dw = drawable.getIntrinsicWidth();
                int dh = drawable.getIntrinsicHeight();
                drawable.setBounds((width - dw) / 2, height - dh, (width + dw) / 2, height);
                drawable.draw(canvas);
            }
        }
    }
}
